package api

import (
	"net/http"
	"schedulingcfg/dao/builder"
	"schedulingcfg/model/db"
	"schedulingcfg/model/dto"
	"schedulingcfg/model/vo"
	"schedulingcfg/utils"

	"github.com/gin-gonic/gin"
)

type SignKeysApi struct {
	BaseApi
}

//签名密钥
func NewSignKeysApi(baseApi BaseApi) {
	m := SignKeysApi{baseApi}

	group := m.router.Group("/signkeys")
	group.GET("/:id", m.Get)             //查询
	group.POST("", m.Post)               //增加
	group.PUT("/edit", m.Put)            //修改
	group.DELETE("/:id", m.Delete)       //删除
	group.PUT("", m.QueryTables)         //查询列表
	group.POST("/select", m.QuerySelect) //查询下拉
}

//查询
func (m *SignKeysApi) Get(c *gin.Context) {
	id := c.Param("id")
	data := new(db.SignKeys)
	err := m.db.First(data, "id = ?", id).Error
	if err != nil {
		utils.FailResult(c, "获取对象失败!")
		return
	}
	c.JSON(http.StatusOK, data)
}

//增加
func (m *SignKeysApi) Post(c *gin.Context) {
	in := new(db.SignKeys)
	if !utils.Bind(c, in) {
		return
	}

	in.Id = m.getId()
	err := m.db.Create(in).Error
	if err != nil {
		utils.FailResult(c, "插入数据失败")
		return
	}
	utils.Success(c)
}

//修改
func (m *SignKeysApi) Put(c *gin.Context) {
	in := new(db.SignKeys)
	if !utils.Bind(c, in) {
		return
	}
	if in.Id == "" {
		utils.FailResult(c, "主键不能为空")
		return
	}
	err := m.db.Where("id = ?", in.Id).Updates(in).Error
	if err != nil {
		utils.FailResult(c, "更新数据失败")
		return
	}
	utils.Success(c)
}

//删除
func (m *SignKeysApi) Delete(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(http.StatusOK, vo.HttpResult{Code: "0001", Msg: "主键不能为空！"})
		return
	}
	err := m.db.Delete(db.SignKeys{}, "id = ?", id).Error
	if err != nil {
		utils.FailResult(c, "删除数据失败!")
		return
	}
	utils.Success(c)
}

//查询列表
func (m *SignKeysApi) QueryTables(c *gin.Context) {
	in := new(struct {
		Page      dto.PageDTO `json:"page"`
		QueryData db.SignKeys `json:"queryData"`
	})
	if !utils.Bind(c, in) {
		return
	}

	q := in.QueryData
	sql, values := builder.Builder().SELECT("*").FROM("sign_keys a").
		NotEmpty("and id = ?", q.Id).Build()
	result := FindPage(m.db, db.SignKeys{}, sql, values, in.Page)
	c.JSON(http.StatusOK, result)
}

//分页下拉
func (m *SignKeysApi) QuerySelect(c *gin.Context) {
	in := make(map[string]string, 0)
	if !utils.Bind(c, &in) {
		return
	}
	sql, _ := builder.Builder().SQL("select id as key_id, pkg as title from sign_keys a").Build()
	values := make([]interface{}, 0)
	values = append(values, in["projectId"])
	result := FindList(m.db, sql, values, dto.PageDTO{1, 100000})
	utils.Success(c, result)
}
